package logic

import (
	"context"
	"encoding/json"
	"fmt"

	"paper-pro/app/paperfile/model"
	"paper-pro/app/paperfile/rpc/internal/svc"
	"paper-pro/app/paperfile/rpc/pb/paperfile"
	"paper-pro/pkg/xerr"

	"github.com/minio/minio-go/v7"
	"github.com/pkg/errors"
	"github.com/zeromicro/go-zero/core/logx"
	"go.mongodb.org/mongo-driver/mongo"
)

var ErrPaperPermissionDenied = xerr.NewErrMsg("没有文件权限")
var ErrDeleteFileFailed = xerr.NewErrMsg("删除文件失败")

type DeleteLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewDeleteLogic(ctx context.Context, svcCtx *svc.ServiceContext) *DeleteLogic {
	return &DeleteLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *DeleteLogic) pushKqDeleteTask(paperMeta *model.Paper) error {
	payload, err := json.Marshal(CopyKqPaperMeta(paperMeta))
	if err != nil {
		return err
	}
	kqTaskMsg := KqPdfTaskInfo{
		TaskType:     PDF_DELETE,
		TaskPlayload: string(payload),
	}
	msgBytes, err := json.Marshal(kqTaskMsg)
	if err != nil {
		return err
	}
	return l.svcCtx.KqPusherClient.PushWithKey(l.ctx, paperMeta.ID.Hex(), string(msgBytes)) // 保证相同文件排在同一分区，从而保证任务的顺序
}

func (l *DeleteLogic) Delete(in *paperfile.DeleteReq) (*paperfile.DeleteResp, error) {
	// 删除简单版：用事务做，懒得做优化了（也可以用mongodb 的 FindOneAndDelete，一口气将删除和鉴权全都做了）
	session, err := l.svcCtx.PaperModel.StartSession()
	if err != nil {
		return nil, errors.Wrapf(err, "Delete: 事务启动失败: %v", err)
	}
	defer session.EndSession(l.ctx)

	data, err := session.WithTransaction(l.ctx, func(sessCtx mongo.SessionContext) (any, error) {
		paperMeta, err := l.svcCtx.PaperModel.FindOne(sessCtx, in.Id)
		if err != nil {
			return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR),
				"Delete: Find paper ID: %s, err:%v", in.Id, err)
		}
		if paperMeta.UserId != in.UserId {
			return nil, errors.Wrapf(ErrPaperPermissionDenied,
				"Delete: paper ID: %s, belong User: %d, op User: %d", in.Id, paperMeta.UserId, in.UserId)
		}

		if err := l.svcCtx.MinioClient.RemoveObject(sessCtx,
			paperMeta.MinIOBucket,
			paperMeta.MinIOObject,
			minio.RemoveObjectOptions{},
		); err != nil {
			return nil, errors.Wrapf(ErrDeleteFileFailed,
				"Delete: paper ID: %s, MinIO RemoveObject error: %v", in.Id, err)
		}

		// 删除向量数据任务发布到消息队列
		if err := l.pushKqDeleteTask(paperMeta); err != nil {
			paperMeta.Status = model.StatusDeleteFailed
			l.svcCtx.PaperModel.Update(context.Background(), paperMeta) // 忽略更新状态过程中的错误
			return nil, errors.Wrapf(err, "Delete: paper ID: %s, push kafka delete task err: %v", in.Id, err)
		}

		_, err = l.svcCtx.PaperModel.Delete(sessCtx, in.Id)
		if err != nil {
			paperMeta.Status = model.StatusDeleteFailed
			l.svcCtx.PaperModel.Update(context.Background(), paperMeta) // 忽略更新状态过程中的错误
			return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR),
				"Delete: paper ID: %s, err: %v", in.Id, err)
		}

		return paperMeta, nil
	})
	if err != nil {
		return nil, err
	}
	var paperMeta *model.Paper
	if meta, ok := data.(*model.Paper); !ok {
		return nil, fmt.Errorf("Delete: convert *model.Paper failed")
	} else {
		paperMeta = meta
	}

	return &paperfile.DeleteResp{
		Meta: &paperfile.PaperFileMeta{
			Id:          paperMeta.ID.Hex(),
			UpdateAt:    paperMeta.UpdateAt.Unix(),
			CreateAt:    paperMeta.CreateAt.Unix(),
			FileName:    paperMeta.FileName,
			FileSize:    paperMeta.FileSize,
			ContentType: paperMeta.ContentType,
			Status:      model.StatusDeleted,
			ParseStatus: paperMeta.ParseStatus,
		},
		VectorDBInfo: &paperfile.VectorDBInfo{
			ParseStatus: paperMeta.ParseStatus,
		},
	}, nil
}
